<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8" />
    <link rel="icon" type="image/svg+xml" href="/super/favicon.ico" />
    <title>添加/编辑科普分类 - 见闻间管理后台</title>
    <link rel="stylesheet" href="/super/assets/index-a23242ca.css">
    <style>
        /* 基础页面样式 */
        body {
            background-color: #121212;
            color: #ffffff;
            margin: 0;
            padding: 0;
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', sans-serif;
        }

        .app-loading {
            position: absolute;
            top: 0px;
            left: 0px;
            right: 0px;
            bottom: 0px;
            display: flex;
            justify-content: center;
            align-items: center;
            flex-direction: column;
            background: #212121;
        }

        .app-loading__loader {
            position: relative;
        }

        .loading__logo {
            position: absolute;
            z-index: 1;
            inset: 10px;
            width: 44px;
            height: 44px;
            border-radius: 50%;
        }

        .loading__loader {
            width: 64px;
            height: 64px;
            border-radius: 50%;
            border: 3px solid rgba(255, 255, 255, 0.1);
            border-left-color: #4CAF50;
            animation: loader-rotate 1s linear infinite;
        }

        @keyframes loader-rotate {
            0% {
                transform: rotate(0);
            }
            100% {
                transform: rotate(360deg);
            }
        }

        .loading__text {
            margin-top: 20px;
            font-size: 14px;
            color: rgba(255, 255, 255, 0.6);
        }

        .container {
            max-width: 600px;
            margin: 0 auto;
            padding: 20px;
        }

        .header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
        }

        .title {
            font-size: 24px;
            font-weight: 600;
        }

        .back-button {
            padding: 8px 16px;
            background-color: #333;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
        }

        .back-button:hover {
            background-color: #444;
        }

        .form-container {
            background-color: #212121;
            padding: 24px;
            border-radius: 8px;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.3);
        }

        .form-group {
            margin-bottom: 20px;
        }

        .form-group label {
            display: block;
            margin-bottom: 8px;
            font-weight: 500;
        }

        .form-input {
            width: 100%;
            padding: 10px;
            background-color: #333;
            border: 1px solid #555;
            border-radius: 4px;
            color: white;
            font-size: 14px;
            box-sizing: border-box;
        }

        .form-input:focus {
            outline: none;
            border-color: #4CAF50;
        }

        .form-actions {
            display: flex;
            justify-content: flex-end;
            gap: 10px;
            margin-top: 30px;
        }

        .btn {
            padding: 10px 20px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
            transition: all 0.3s;
        }

        .btn-primary {
            background-color: #4CAF50;
            color: white;
        }

        .btn-primary:hover {
            background-color: #45a049;
        }

        .btn-secondary {
            background-color: #555;
            color: white;
        }

        .btn-secondary:hover {
            background-color: #666;
        }

        .error-message {
            color: #ff4444;
            margin-top: 5px;
            font-size: 12px;
        }

        .loading-overlay {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background-color: rgba(0, 0, 0, 0.6);
            justify-content: center;
            align-items: center;
            z-index: 1000;
        }

        .loading-content {
            background-color: #212121;
            padding: 20px;
            border-radius: 4px;
            text-align: center;
        }

        .loading-spinner {
            border: 3px solid rgba(255, 255, 255, 0.1);
            border-left-color: #4CAF50;
            border-radius: 50%;
            width: 30px;
            height: 30px;
            animation: loader-rotate 1s linear infinite;
            margin: 0 auto 10px;
        }
    </style>
</head>

<body>
    <div id="loading" class="app-loading">
        <div class="app-loading__loader">
            <div class="loading__loader"></div>
        </div>
        <div class="loading__text">加载中...</div>
    </div>

    <div class="loading-overlay" id="loading-overlay">
        <div class="loading-content">
            <div class="loading-spinner"></div>
            <div>处理中...</div>
        </div>
    </div>

    <div class="container" style="display: none;">
        <div class="header">
            <h1 class="title" id="page-title">添加科普分类</h1>
            <button class="back-button" onclick="window.location.href='/super#/science/category/index'">返回列表</button>
        </div>
        
        <div class="form-container">
            <form id="category-form">
                <!-- 隐藏的ID字段，用于编辑模式 -->
                <input type="hidden" id="category-id" name="id">
                
                <div class="form-group">
                    <label for="category-name">分类名称 <span style="color: #ff4444;">*</span></label>
                    <input type="text" id="category-name" name="name" class="form-input" placeholder="请输入分类名称" required>
                    <div class="error-message" id="name-error"></div>
                </div>
                
                <div class="form-actions">
                    <button type="button" class="btn btn-secondary" onclick="window.location.href='/super#/science/category/index'">取消</button>
                    <button type="button" id="save-button" class="btn btn-primary">保存</button>
                </div>
            </form>
        </div>
    </div>

    <script>
        // 页面加载完成后执行
        document.addEventListener('DOMContentLoaded', function() {
            // 隐藏加载动画，显示页面内容
            setTimeout(function() {
                document.getElementById('loading').style.display = 'none';
                document.querySelector('.container').style.display = 'block';
            }, 500);

            // 获取URL参数
            const urlParams = new URLSearchParams(window.location.search);
            const categoryId = urlParams.get('id');
            
            // 如果存在ID参数，则为编辑模式
            if (categoryId) {
                document.getElementById('page-title').textContent = '编辑科普分类';
                loadCategoryData(categoryId);
            }

            // 保存按钮点击事件
            document.getElementById('save-button').addEventListener('click', function() {
                saveCategory();
            });

            // 表单提交事件（防止默认提交）
            document.getElementById('category-form').addEventListener('submit', function(e) {
                e.preventDefault();
                saveCategory();
            });
        });

        // 加载分类数据
        function loadCategoryData(id) {
            showLoading();
            
            // 调用详情接口获取分类数据
            fetch(`/science/api/categories?id=${id}`)
                .then(response => {
                    if (!response.ok) {
                        throw new Error('网络请求失败');
                    }
                    return response.json();
                })
                .then(data => {
                    hideLoading();
                    
                    if (data.code === 200 || data.code === 0) {
                        // 适配数据结构，根据CategoryService->select()方法的返回格式
                        // select方法返回的是数组，我们需要找到匹配的那一项
                        let category = {};
                        if (Array.isArray(data.data)) {
                            // 如果是数组，查找ID匹配的项
                            const found = data.data.find(item => item.id === parseInt(id));
                            if (found) {
                                category = found;
                            }
                        } else if (data.data && typeof data.data === 'object') {
                            // 如果是对象，直接使用
                            category = data.data;
                        }
                        
                        document.getElementById('category-id').value = category.id || '';
                        document.getElementById('category-name').value = category.name || '';
                    } else {
                        alert('获取分类数据失败：' + (data.msg || '未知错误'));
                        // 如果获取失败，返回列表页
                        setTimeout(() => {
                            window.location.href = '/super#/science/category/index';
                        }, 1500);
                    }
                })
                .catch(error => {
                    hideLoading();
                    console.error('加载分类数据失败：', error);
                    alert('加载分类数据失败，请稍后重试');
                    // 如果获取失败，返回列表页
                    setTimeout(() => {
                        window.location.href = '/super#/science/category/index';
                    }, 1500);
                });
        }

        // 保存分类
        function saveCategory() {
            // 验证表单
            const name = document.getElementById('category-name').value.trim();
            const nameError = document.getElementById('name-error');
            
            if (!name) {
                nameError.textContent = '请输入分类名称';
                return;
            }
            
            if (name.length > 50) {
                nameError.textContent = '分类名称不能超过50个字符';
                return;
            }
            
            // 过滤HTML特殊字符
            const filteredName = name.replace(/</g, '＜').replace(/>/g, '＞');
            nameError.textContent = '';

            // 准备提交数据
            const id = document.getElementById('category-id').value;
            
            // 创建FormData对象
            const formData = new FormData();
            formData.append('name', filteredName);

            showLoading();

            // 确定API地址和方法
            const isEditMode = !!id;
            let apiUrl = '/science/api/category/create';
            if (isEditMode) {
                apiUrl = `/science/api/category/update?id=${id}`;
            }

            fetch(apiUrl, {
                method: 'POST',
                body: formData
            })
                .then(response => {
                    if (!response.ok) {
                        throw new Error('网络请求失败');
                    }
                    return response.json();
                })
                .then(data => {
                    hideLoading();
                    
                    if (data.code === 200 || data.code === 0) {
                        alert(isEditMode ? '编辑成功' : '添加成功');
                        window.location.href = '/super#/science/category/index';
                    } else {
                        alert('保存失败：' + (data.msg || '未知错误'));
                    }
                })
                .catch(error => {
                    hideLoading();
                    console.error('保存分类失败：', error);
                    alert('保存分类失败，请稍后重试');
                });
        }

        // 显示加载状态
        function showLoading() {
            document.getElementById('loading-overlay').style.display = 'flex';
        }

        // 隐藏加载状态
        function hideLoading() {
            document.getElementById('loading-overlay').style.display = 'none';
        }
    </script>
</body>

</html>